#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<unistd.h>
#include<cstring>
#include<string>
#include<sys/types.h>
#include<sys/wait.h>

#define FORMAT "[%s@%s %s]# "
#define COMMAND_SIZE 1024

#define MAXARGV 128
char *g_argv[MAXARGV];
int g_argc;

char cwd[1024];
char cwdenv[1024];

#define MAX_ENVS 100
char *g_env[MAX_ENVS];
int g_envs = 0;

int lastcode = 0;

const char *GetUserName (){
    const char *username = getenv("USER");
    return username == NULL ? "None":username;
}
const char *GetHostName (){
    const char *hostname = getenv("HOSTNAME");
    return hostname == NULL ? "None":hostname; 
}
void InitEnv(){
    extern char **environ;

    memset(g_env,0,sizeof(g_env));
    g_envs = 0;
    for(int i = 0; environ[i];i++){
        g_env[i] = (char*)malloc(strlen(environ[i])+1);
        g_env[g_envs]=environ[i];
        g_envs++;
    }
    g_env[g_envs++]=(char*)"HAHA=for_test";
    g_env[g_envs] = NULL;
    for(int i = 0; g_env[i];i++){
        putenv(g_env[i]);
    }
    environ = g_env;

}
const char *GetPwd (){

    const char *pwd = getcwd(cwd,sizeof(cwd));
    if(pwd!=NULL){
        snprintf(cwdenv,sizeof(cwdenv),"PWD=%s",cwd);
        putenv(cwdenv);
    }
    return pwd == NULL ? "None":pwd;
}
const char *GetHome(){
    const char *home = getenv("HOME");
    return home == NULL ? "":home;
}

void cd(){
    if(g_argc == 1){
        std::string home = GetHome();
        if(home.empty()) return; 
        chdir(home.c_str());
    }
    else{
        std::string where = g_argv[1];
        chdir(where.c_str());
    }
}
void echo(){
    std::string cmd = g_argv[1];
    if(cmd == "$?"){
        std::cout<<lastcode<<std::endl;
        lastcode=0;
    }
    else if(cmd[0] == '$'){
        std::string env_name = cmd.substr(1); 
        const char * env_val = getenv(env_name.c_str());
        if(env_val!=NULL)
            std::cout<<env_val<<std::endl;
    } 
    else{
        std::cout<<cmd<<std::endl;
    }
}

void MakeCommandPrompt(char *prompt,int size){
    snprintf(prompt,size,FORMAT,GetUserName(),GetHostName(),GetPwd());
}

void PrintCommandPrompt(){
    char prompt[COMMAND_SIZE];
    MakeCommandPrompt(prompt,sizeof(prompt));
    printf("%s",prompt);
    fflush(stdout);
}

bool GetCommandLine(char *commandline,int size){
    char *c = fgets(commandline,size,stdin);
    if(c==NULL) return false;
    commandline[strlen(commandline)-1] = 0;
    if(strlen(commandline)==0) return false;
    return true;
}

bool CommandPrase(char *command){
#define SEP " "
    g_argc = 0;
    g_argv[g_argc++] = strtok(command,SEP);
    while((bool)(g_argv[g_argc++] = strtok(nullptr,SEP)));
    g_argc--;
    return true;
}

bool CheckAndBuiltin(){
    std::string cmd = g_argv[0];
    if(cmd == "cd"){
        cd();
        return true;
    }
    else if(cmd == "echo"){
        echo();
        return true;
    }
    return false;
}

int Execute(){
    pid_t id = fork();
    if(id == 0){
        execvp(g_argv[0],g_argv);
        exit(1);
    }
    int status = 0;
    pid_t rid = waitpid(id,&status,0);
    if(rid>0){
        lastcode = WEXITSTATUS(status);
    }
    return 0;
}

int main(){
    InitEnv();
    while(true){
        //1.输出命令行格式
        PrintCommandPrompt();
        //2.接收命令输入
        char commandline[COMMAND_SIZE];
        if(!GetCommandLine(commandline,sizeof(commandline)))
            continue;
        //3.命令行分析
        CommandPrase(commandline);
        //4.内建命令识别和处理
        if(CheckAndBuiltin())
            continue;
        //5.执行命令
        Execute();
    }
    return 0;
}
